﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections.Generic;

using SKYPE4COMLib;
using skypeConnector.Model;


namespace skypeConnector
{
    public partial class Form1 : Form
    {
        public class MyKeyValuePairSex
        {
            public TUserSex Key;
            public string Value;

            public MyKeyValuePairSex(TUserSex NewKey, string NewValue)
            {
                Key = NewKey;
                Value = NewValue;
            }

            public override string ToString()
            {
                return Value;
            }
        }

        public class MyKeyValuePairCountry
        {
            public string Key;
            public string Value;

            public MyKeyValuePairCountry(string NewKey, string NewValue)
            {
                Key = NewKey;
                Value = NewValue;
            }

            public override string ToString()
            {
                return Value;
            }
        }

        SkypeUtil skypeUtil;
        string SC_VERSION = "1.0.1";

        public Form1()
        {
            InitializeComponent();
            fillComboBoxSex(find_sex_comboBox);
            fillComboBoxCountry(find_country_comboBox);
            skypeUtil = new SkypeUtil();
            statusStrip1.Visible = false;
            menuStrip1.Visible = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            refreshSkypeFriends();
        }

        private void refreshSkypeFriends()
        {
            comboBox1.Items.Clear();
            find_result_comboBox_groups.Items.Clear();
            groups_tree.Nodes.Clear();
            fillTreeView();
            find_sex_comboBox.SelectedIndex = 0;
            find_country_comboBox.SelectedIndex = 0;
        }

        private void addGroupToComboBox(ComboBox box, Group group)
        {
            box.Items.Add(group.DisplayName);
        }

        private void fillTreeView()
        {
            addGroupsToTreeView(skypeUtil.getAllCustomGroups());
            foreach (User user in skypeUtil.getFrieds())
            {
                if (!skypeUtil.isUserInGroups(user))
                {
                    addFriendToTreeView(user);
                }
            }
        }

        private void addGroupsToTreeView(GroupCollection groups)
        {
            foreach (Group group in groups)
            {
                addGroupToTreeView(group);
            }
        }

        private void addGroupToTreeView(Group group)
        {
            addGroupToComboBox(comboBox1, group);
            addGroupToComboBox(find_result_comboBox_groups, group);
            TreeNode node;
            node = groups_tree.Nodes.Add(group.DisplayName);
            node.ImageIndex = 2;
            addFriendsToTreeNode(node, group.Users);
        }

        private void addFriendsToTreeView(UserCollection users)
        {
            foreach (User user in users)
            {
                addFriendToTreeView(user);
            }
        }

        private void addFriendsToTreeNode(TreeNode node, UserCollection users)
        {
            foreach (User user in users)
            {
                addFriendToTreeNode(node, user);
            }
        }

        private void addFriendToTreeView(User user)
        {
            if (user.IsAuthorized)
            {
                TreeNode node;
                node = groups_tree.Nodes.Add(skypeUtil.getUserNameToDispaly(user));
                node.Tag = user.Handle;
                if (skypeUtil.isUserOnline(user))
                    node.ImageIndex = 0;
                else
                    node.ImageIndex = 1;
            }
        }

        private void addFriendToTreeNode(TreeNode node, User user)
        {
            if (user.IsAuthorized)
            {
                TreeNode child;
                child = node.Nodes.Add(skypeUtil.getUserNameToDispaly(user));
                child.Tag = user.Handle;
                if (skypeUtil.isUserOnline(user))
                    child.ImageIndex = 0;
                else
                    child.ImageIndex = 1;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string groupName = textBox1.Text;
            if (groupName.Length == 0)
            {
                MessageBox.Show("Укажите название группы", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (skypeUtil.isGroupExists(groupName))
            {
                MessageBox.Show("Такая группа уже существует", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            skypeUtil.addGroup(groupName);
            textBox1.Text = "";
            groups_tree.Nodes.Clear();
            comboBox1.Items.Clear();
            find_result_comboBox_groups.Items.Clear();
            skypeUtil.refreshCustomGroups();
            groups_tree.BeginUpdate();
            fillTreeView();
            groups_tree.EndUpdate();
        }

        private void оПрограммеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string about = "Это приложение использует программу Skype (5.0 и выше)\n";
            about += "Автор: Кондратенко Максим (max.kondr@gmail.com)\n";
            about += "Версия: " + SC_VERSION;
            MessageBox.Show(about, "О программе", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex == -1)
            {
                MessageBox.Show("Выберете группу для удаления", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (!skypeUtil.isGroupExists(comboBox1.SelectedItem.ToString()))
            {
                MessageBox.Show("Выбранная группа не существует", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                skypeUtil.deleteGroup(comboBox1.SelectedItem.ToString());
                comboBox1.SelectedIndex = -1;
                groups_tree.Nodes.Clear();
                comboBox1.Items.Clear();
                find_result_comboBox_groups.Items.Clear();
                skypeUtil.refreshCustomGroups();
                fillTreeView();
            }

        }

        private void groups_tree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (groups_tree.SelectedNode != null)
            {
                groups_tree.BeginUpdate();
                groups_tree.SelectedImageIndex = groups_tree.SelectedNode.ImageIndex;
                groups_tree.EndUpdate();
                if (groups_tree.SelectedNode.Tag != null)
                {
                    User user = skypeUtil.getUserBySkypeId(groups_tree.SelectedNode.Tag.ToString());
                    if (user != null)
                    {
                        id_textBox.Text = user.Handle;
                        name_textBox.Text = user.FullName;
                        birthday_textBox.Text = skypeUtil.getDateString(user.Birthday);
                        country_textBox.Text = user.Country;
                        city_textBox.Text = user.City;
                        language_textBox.Text = user.Language;
                    }
                }
                else
                    clearUserInfoComponents();
            }
        }

        private void clearUserInfoComponents()
        {
            id_textBox.Text = "";
            name_textBox.Text = "";
            birthday_textBox.Text = "";
            country_textBox.Text = "";
            city_textBox.Text = "";
            language_textBox.Text = "";
        }

        private void find_find_button_Click(object sender, EventArgs e)
        {
            if (!find_result_checkbox_add_results.Checked)
                find_result_listView.Items.Clear();
            if (find_firstName_textBox.Text.Length == 0)
            {
                MessageBox.Show("Задайте имя для поиска", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            toolStripStatusLabel2.Text = "Поиск...";
            toolStripStatusLabel4.Text = "";
            System.Windows.Forms.Application.DoEvents();
            UserCollection userCol = skypeUtil.findUsersByFirstName(find_firstName_textBox.Text);
            UserCollection userCol_final = new UserCollection();
            userCol = skypeUtil.filterUsersBySex(((MyKeyValuePairSex)find_sex_comboBox.SelectedItem).Key, userCol);
            if (find_country_comboBox.SelectedIndex != 0)
            {
                UserCollection userCol_tmp = skypeUtil.filterUsersByCountry(((MyKeyValuePairCountry)find_country_comboBox.SelectedItem).Key, userCol);
                foreach (User u in userCol_tmp)
                    userCol_final.Add(u);
                userCol_tmp = skypeUtil.filterUsersByCountry(((MyKeyValuePairCountry)find_country_comboBox.SelectedItem).Value, userCol);
                foreach (User u in userCol_tmp)
                    userCol_final.Add(u);
            }
            else
            {
                userCol_final = userCol;
            }
            foreach (User user in userCol_final)
            {
                find_result_listView.Items.Add(new ListViewItem(new string[] 
                        { user.Handle, user.FullName, 
                            user.Country, user.City, skypeUtil.getUserSexToDisplay(user.Sex)}));
            }
            toolStripStatusLabel4.Text = userCol_final.Count.ToString();
            toolStripStatusLabel2.Text = "Поиск завершен";
        }

        private void выходToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Application.Exit();
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            skypeUtil.refreshCustomGroups();
            refreshSkypeFriends();
        }

        private void fillComboBoxSex(ComboBox box)
        {
            box.Items.Add(new MyKeyValuePairSex(TUserSex.usexUnknown, "Не имеет значения"));
            box.Items.Add(new MyKeyValuePairSex(TUserSex.usexMale, "Мужской"));
            box.Items.Add(new MyKeyValuePairSex(TUserSex.usexFemale, "Женский"));
        }

        private void fillComboBoxCountry(ComboBox box)
        {
            box.Items.Add(new MyKeyValuePairCountry("", "Не имеет значения"));
            box.Items.Add(new MyKeyValuePairCountry("Russia", "Россия"));
            box.Items.Add(new MyKeyValuePairCountry("Ukraine", "Украина"));
            box.Items.Add(new MyKeyValuePairCountry("Belarus", "Беларусь"));
            box.Items.Add(new MyKeyValuePairCountry("Kazakhstan", "Казахстан"));
            box.Items.Add(new MyKeyValuePairCountry("Moldova", "Молдавия"));
        }

        private void tabControl1_Selected(object sender, TabControlEventArgs e)
        {
            if (tabControl1.SelectedIndex == 1)
                statusStrip1.Visible = true;
            else
                statusStrip1.Visible = false;
            toolStripStatusLabel2.Text = "";
            toolStripStatusLabel4.Text = "";
        }

        private void find_result_button_clear_Click(object sender, EventArgs e)
        {
            find_result_listView.Items.Clear();
        }

        private void find_result_checkBox_select_all_CheckStateChanged(object sender, EventArgs e)
        {
            if (find_result_checkBox_select_all.Checked && find_result_listView.Items.Count > 0)
                foreach (ListViewItem it in find_result_listView.Items)
                    it.Checked = true;
        }

        private void find_result_add_to_group_button_Click(object sender, EventArgs e)
        {
            if (find_result_listView.CheckedItems.Count == 0)
            {
                MessageBox.Show("Выберите контакты для добавления в группу", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (find_result_comboBox_groups.SelectedIndex == -1)
            {
                MessageBox.Show("Выберите группу для добавления контактов", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            List<string> userList = new List<string>();
            foreach (ListViewItem item in find_result_listView.CheckedItems)
            {
                userList.Add(item.Text);
            }
            string groupName = find_result_comboBox_groups.SelectedItem.ToString();
            skypeUtil.addUsersToGroup(groupName, userList);
            refreshSkypeFriends();
            string mes = "Добавленно " + userList.Count + " контактов в группу " + groupName;
            MessageBox.Show(mes, "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }



    }
}
